from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render

from lianxi20250912.models import device


# Create your views here.
def get_devices_list(request):
    data=device.objects.all()
    l=[]
    type=request.GET.get('type')
    status=request.GET.get('status')
    location=request.GET.get('location')
    page=request.GET.get('page',1)
    size=request.GET.get('size') or 20
    if type:
        data=data.filter(type=type)
    if status:
        data=data.filter(status=status)
    if location:
        data=data.filter(location=location)
    total=len(data)
    data=Paginator(data,size).get_page(page)
    for i in data:
        l.append(
            {
                'id':i.id,
                'serial_no':i.serial_no,
                'name':i.name,
                'type':i.type,
                'location':i.location,
                'status':i.status,
                'purchase_data':i.purchase_date,
                'last_check':i.last_check
            }
        )
    return JsonResponse(
        {
            'items':l,
            'total':total,
            'page':1
        }
    )

def get_devices_detail(request,id=None):
        if id == None:
            return JsonResponse(
                {
                    'msg': 'id必传'

                }
            )
        data = device.objects.get(id=id)
        l={
            'id':data.id,
            'serial_no':data.serial_no,
            'status':data.status,
            'last_check':data.last_check
        }
        return JsonResponse(
            {
                'data':l
            }
        )
